package com.practice.springboot_01_zwj.service.impl;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.practice.springboot_01_zwj.entity.BatchSubTask;
import com.practice.springboot_01_zwj.entity.dto.*;
import com.practice.springboot_01_zwj.entity.AccountInfo;
import com.practice.springboot_01_zwj.entity.MainTask;
import com.practice.springboot_01_zwj.entity.SubTask;
import com.practice.springboot_01_zwj.mapper.AccountInfoMapper;
import com.practice.springboot_01_zwj.mapper.BatchSubTaskMapper;
import com.practice.springboot_01_zwj.mapper.MainTaskMapper;
import com.practice.springboot_01_zwj.mapper.SubTaskMapper;
import com.practice.springboot_01_zwj.service.TaskService;
import io.micrometer.common.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl implements TaskService {

    @Autowired
    private MainTaskMapper mainTaskMapper;

    @Autowired
    private SubTaskMapper subTaskMapper;
    @Autowired
    private AccountInfoMapper accountMapper;
    @Autowired
    private BatchSubTaskMapper batchSubTaskMapper;


    @Override
    public Integer createMainTask(MainTask mainTask) {
        // 设置初始值
        mainTask.setTaskState(0);
        mainTask.setTaskProgress(0.0);
        mainTask.setTaskImplementation("落后");

        // 计算初始时间进度
        Date now = new Date();
        if (mainTask.getPlanBeginTime() != null && mainTask.getPlanEndTime() != null) {
            if (now.before(mainTask.getPlanBeginTime())) {
                mainTask.setTimeProgress(0.0);
            } else if (now.after(mainTask.getPlanEndTime())) {
                mainTask.setTimeProgress(100.0);
            } else {
                long total = mainTask.getPlanEndTime().getTime() - mainTask.getPlanBeginTime().getTime();
                long elapsed = now.getTime() - mainTask.getPlanBeginTime().getTime();
                double progress = (double) elapsed / total * 100;
                mainTask.setTimeProgress(progress);
            }
        } else {
            mainTask.setTimeProgress(0.0);
        }

        mainTaskMapper.insert(mainTask);
        return mainTask.getMainId();
    }

    @Override
    @Transactional
    //添加子任务
    public void addSubtasks(Integer mainId, List<SubTask> subTasks) {
        // 确保主任务存在
        MainTask mainTask = mainTaskMapper.selectById(mainId);
        if (mainTask == null) {
            throw new IllegalArgumentException("主任务不存在");
        }

        // 设置每个子任务的主任务ID
        for (SubTask subTask : subTasks) {
            subTask.setMainId(mainId);
            // 初始化子任务进度为0
            subTask.setFinishProgress(0.0);
        }

        // 批量插入子任务
        if (!subTasks.isEmpty()) {
            subTaskMapper.batchInsert(subTasks);
        }

        // 更新主任务进度（因为现在有子任务了）
        updateMainTaskProgressAndState(mainId);
        updateMainTaskProgressAndState(mainId);
    }
//    @Override
//    @Transactional
//    //创建主任务和子任务
//    public Integer createMainTaskWithSubtasks(MainTask mainTask, List<SubTask> subTasks) {
//        // 插入主任务
//        mainTaskMapper.insert(mainTask);
//        Integer mainId = mainTask.getMainId();
//
//        // 设置子任务的主任务ID
//        if (subTasks != null && !subTasks.isEmpty()) {
//            for (SubTask subTask : subTasks) {
//                subTask.setMainId(mainId);
//                // 初始化子任务进度为0
//                subTask.setFinishProgress(0);
//            }
//            subTaskMapper.batchInsert(subTasks);
//        }
//
//        // 移除此调用 → updateMainTaskProgressAndState(mainId);
//        return mainId;
//    }

   //更新主任务
    @Override
    public void updateMainTask(MainTask mainTask) {
        // 检查任务是否可编辑
        if (mainTaskMapper.checkEditable(mainTask.getMainId()) == 0) {
            throw new IllegalStateException("任务已完成或终止，不可编辑");
        }

        // 获取更新前的任务状态
        MainTask originalTask = mainTaskMapper.selectById(mainTask.getMainId());

        // 执行更新
        mainTaskMapper.update(mainTask);

        // 如果修改了计划时间，需要重新计算状态
        if (dateChanged(originalTask, mainTask)) {
            // 重新获取完整的主任务对象
            MainTask updatedTask = mainTaskMapper.selectById(mainTask.getMainId());
            // 重新计算状态
            recalculateTaskState(updatedTask);
            // 更新状态
            mainTaskMapper.updateProgressAndState(updatedTask);
        }
    }
    // 检查计划时间是否发生变化
    private boolean dateChanged(MainTask original, MainTask updated) {
        if (original == null || updated == null) return false;

        // 检查开始时间是否变化
        if (original.getPlanBeginTime() == null && updated.getPlanBeginTime() != null) return true;
        if (original.getPlanBeginTime() != null && updated.getPlanBeginTime() == null) return true;
        if (original.getPlanBeginTime() != null && updated.getPlanBeginTime() != null &&
                !original.getPlanBeginTime().equals(updated.getPlanBeginTime())) return true;

        // 检查结束时间是否变化
        if (original.getPlanEndTime() == null && updated.getPlanEndTime() != null) return true;
        if (original.getPlanEndTime() != null && updated.getPlanEndTime() == null) return true;
        if (original.getPlanEndTime() != null && updated.getPlanEndTime() != null &&
                !original.getPlanEndTime().equals(updated.getPlanEndTime())) return true;

        return false;
    }

    // 重新计算任务状态
    private void recalculateTaskState(MainTask task) {
        Date now = new Date();

        // 重置状态为未开始（后续会根据时间重新计算）
        task.setTaskState(0);

        // 重新计算时间进度
        calculateTimeProgress(task);

        // 状态转换逻辑
        // 状态0 -> 1：当前时间到达计划开始时间
        if (task.getTaskState() == 0 &&
                now.compareTo(task.getPlanBeginTime()) >= 0) {
            task.setTaskState(1); // 进行中
        }

        // 状态1 -> 3：当前时间超过计划结束时间的23:59:59
        if (task.getTaskState() == 1 && task.getPlanEndTime() != null) {
            // 获取计划结束日期的23:59:59
            Calendar cal = Calendar.getInstance();
            cal.setTime(task.getPlanEndTime());
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 999);
            Date endOfDay = cal.getTime();

            if (now.after(endOfDay)) {
                task.setTaskState(3); // 已延期
            }
        }

        // 计算落实情况
        double progressDiff = task.getTaskProgress() - task.getTimeProgress();
        if (progressDiff > 5) {
            task.setTaskImplementation("超前");
        } else if (progressDiff < -5) {
            task.setTaskImplementation("落后");
        } else {
            task.setTaskImplementation("正常");
        }
    }

    // 完成任务（优化版）
    @Override
    public void completeMainTask(MainTask task) {
    /*
    // 对于非70类型的任务，检查子任务完成情况
    if (!"70".equals(task.getTaskType())) {
        if (subTaskMapper.countIncompleteSubtasks(task.getMainId()) > 0) {
            throw new IllegalStateException("存在未完成的子目标，无法完成主目标");
        }
    }
    */

        // 公共完成逻辑
        mainTaskMapper.completeTask(task.getMainId(), new Date());
        mainTaskMapper.updateProgress(task.getMainId(), 100.0);
    }

    //终止任务
    @Override
    public void terminateMainTask(Integer mainId) {
        // 检查任务是否可终止 (状态不是2-已完成 或 4-已终止)
        MainTask task = mainTaskMapper.selectById(mainId);
        if (task.getTaskState() == 2 || task.getTaskState() == 4) {
            throw new IllegalStateException("任务已完成或已终止，不可再次终止");
        }
        mainTaskMapper.terminateTask(mainId);
    }

    //主任务执行人获取任务
    @Override
    public List<MainTask> getTasksByExecutor(String executor) {
        return mainTaskMapper.selectByExecutor(executor);
    }


    //更新子任务
    @Override
    @Transactional
    public void updateSubTaskProgress(SubTask subTask) {
        // 1. 获取完整子任务信息（包含主任务ID）
        SubTask existingSubTask = subTaskMapper.selectById(subTask.getSubId());
        if (existingSubTask == null) {
            throw new RuntimeException("子任务不存在");
        }

        // 2. 获取主任务信息
        MainTask mainTask = mainTaskMapper.selectById(existingSubTask.getMainId());
        if (mainTask == null) {
            throw new RuntimeException("关联的主任务不存在");
        }

        // 3. 时间验证（使用主任务的时间范围）
        validateSubTaskDates(
                Collections.singletonList(convertToRequest(subTask, existingSubTask)),
                mainTask.getPlanBeginTime(),
                mainTask.getPlanEndTime()
        );

        // 4. 更新子任务
        int rows = subTaskMapper.update(subTask);
        if (rows == 0) {
            throw new RuntimeException("子任务更新失败");
        }

        // 5. 更新主任务进度和状态
        updateMainTaskProgressAndState(existingSubTask.getMainId());
    }

    // 辅助方法：将 SubTask 转换为 SubTaskRequest
    private SubTaskRequest convertToRequest(SubTask subTask, SubTask existingSubTask) {
        SubTaskRequest request = new SubTaskRequest();
        request.setSubName(subTask.getSubName());
        request.setSubDescription(subTask.getSubDescription());
        request.setSubExecutors(subTask.getSubExecutors());
        request.setPlanStartTime(subTask.getPlanStartTime() != null ?
                subTask.getPlanStartTime() : existingSubTask.getPlanStartTime());
        request.setPlanFinishTime(subTask.getPlanFinishTime() != null ?
                subTask.getPlanFinishTime() : existingSubTask.getPlanFinishTime());
        return request;
    }

    // 子任务时间范围验证方法（复用主任务的验证逻辑）
    private void validateSubTaskDates(List<SubTaskRequest> subTasks, Date mainStart, Date mainEnd) {
        if (subTasks == null) return;

        for (SubTaskRequest sub : subTasks) {
            // 检查开始时间是否早于主任务开始时间
            if (sub.getPlanStartTime() != null && mainStart != null &&
                    sub.getPlanStartTime().before(mainStart)) {
                throw new IllegalArgumentException("子任务开始时间不能早于主任务开始时间: " +
                        formatDate(mainStart));
            }

            // 检查结束时间是否晚于主任务结束时间
            if (sub.getPlanFinishTime() != null && mainEnd != null &&
                    sub.getPlanFinishTime().after(mainEnd)) {
                throw new IllegalArgumentException("子任务结束时间不能晚于主任务结束时间: " +
                        formatDate(mainEnd));
            }

            // 检查开始时间是否晚于结束时间
            if (sub.getPlanStartTime() != null && sub.getPlanFinishTime() != null &&
                    sub.getPlanStartTime().after(sub.getPlanFinishTime())) {
                throw new IllegalArgumentException("子任务开始时间不能晚于结束时间");
            }
        }
    }

    // 日期格式化方法
    private String formatDate(Date date) {
        if (date == null) return "无限制";
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }
    /**
     * 更新主任务进度和状态
     * @param mainId 主任务ID
     */
    @Override
    public void updateMainTaskProgressAndState(Integer mainId) {
        // 调用进度计算方法
        calculateAndUpdateProgress(mainId);
    }

    // 在删除子任务服务方法中调用更新
    @Transactional
    @Override
    public void deleteSubTask(Integer subId) {
        // 1. 获取子任务信息
        SubTask subTask = subTaskMapper.selectById(subId);
        if (subTask == null) {
            throw new RuntimeException("子任务不存在");
        }

        // 2. 删除子任务
        int result = subTaskMapper.deleteById(subId);
        if (result == 0) {
            throw new RuntimeException("删除子任务失败");
        }

        // 3. 重新计算主任务进度和状态
        updateMainTaskProgressAndState(subTask.getMainId());
    }
    @Override
    public void calculateAndUpdateProgress(Integer mainId) {
        try {
            MainTask mainTask = mainTaskMapper.selectById(mainId);
            if (mainTask == null) return;

            List<SubTask> subTasks = subTaskMapper.findByMainId(mainId);

            // 计算平均进度
            double avgProgress = 0.0;
            if (!subTasks.isEmpty()) {
                double totalProgress = 0.0;
                for (SubTask sub : subTasks) {
                    totalProgress += sub.getFinishProgress();
                }
                avgProgress = totalProgress / subTasks.size();
            }

            // 自动更新任务状态和落实情况
            updateTaskStateAutomatically(mainTask, avgProgress);

            // 创建更新对象
            MainTask updateTask = new MainTask();
            updateTask.setMainId(mainId);
            updateTask.setTaskProgress(avgProgress);
            updateTask.setTimeProgress(mainTask.getTimeProgress());
            updateTask.setTaskState(mainTask.getTaskState());
            updateTask.setTaskImplementation(mainTask.getTaskImplementation());
            updateTask.setDeptName(mainTask.getDeptName());

            if (mainTask.getTaskState() == 2) {
                updateTask.setActualFinishTime(mainTask.getActualFinishTime());
            }

            // 更新数据库
            mainTaskMapper.updateProgressAndState(updateTask);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 自动更新任务状态和时间进度
     * @param mainTask 主任务对象（会被修改）
     * @param avgProgress 当前平均进度
     */
    private void updateTaskStateAutomatically(MainTask mainTask, Double avgProgress) {
        // 处理可能的空值状态
        if (mainTask.getTaskState() == null) {
            mainTask.setTaskState(0); // 默认为未开始状态
        }

        // 1. 计算时间进度
        calculateTimeProgress(mainTask);

        // 2. 状态转换逻辑
        Date now = new Date();

        // 状态0 -> 1：当前时间到达计划开始时间
        if (mainTask.getTaskState() == 0 &&
                now.compareTo(mainTask.getPlanBeginTime()) >= 0) {
            mainTask.setTaskState(1); // 进行中
        }

        // 状态1 -> 3：当前时间超过计划结束时间的23:59:59
        if (mainTask.getTaskState() == 1 && mainTask.getPlanEndTime() != null) {
            // 获取计划结束日期的23:59:59
            Calendar cal = Calendar.getInstance();
            cal.setTime(mainTask.getPlanEndTime());
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 999);
            Date endOfDay = cal.getTime();

            if (now.after(endOfDay)) {
                mainTask.setTaskState(3); // 已延期
            }
        }

//        // 如果所有子任务都已完成，自动完成任务
//        if (avgProgress != null && avgProgress >= 100.0) {
//            if (mainTask.getTaskState() != 2) { // 如果不是已完成状态
//                mainTask.setTaskState(2);
//                mainTask.setTaskImplementation("已完成");
//                mainTask.setActualFinishTime(new Date());
//            }
//        }

        // 3. 计算落实情况
        double progressDiff = 0.0;
        if (avgProgress != null) {
            progressDiff = avgProgress - mainTask.getTimeProgress();
        }

        if (progressDiff > 5) {
            mainTask.setTaskImplementation("超前");
        } else if (progressDiff < -5) {
            mainTask.setTaskImplementation("落后");
        } else {
            mainTask.setTaskImplementation("正常");
        }
    }
    /**
     * 计算时间进度百分比
     * @param mainTask 主任务对象
     */
    private void calculateTimeProgress(MainTask mainTask) {

        if (mainTask.getPlanBeginTime() == null || mainTask.getPlanEndTime() == null) {
            mainTask.setTimeProgress(0.0);
            return;
        }

        Date now = new Date();
        long totalDuration = mainTask.getPlanEndTime().getTime() - mainTask.getPlanBeginTime().getTime();

        // 任务尚未开始
        if (now.before(mainTask.getPlanBeginTime())) {
            mainTask.setTimeProgress(0.0);
            return;
        }

        // 任务已结束
        if (now.after(mainTask.getPlanEndTime())) {
            mainTask.setTimeProgress(100.0);
            return;
        }

        // 计算进行中的时间进度
        long elapsed = now.getTime() - mainTask.getPlanBeginTime().getTime();
        double progress = (double) elapsed / totalDuration * 100;
        mainTask.setTimeProgress(Math.min(100.0, Math.max(0.0, progress)));
    }


    /**
     * 检查任务是否应标记为延期
     */
    private boolean shouldMarkAsDelayed(MainTask mainTask) {
        // 任务已完成或已终止时不标记延期
        if (mainTask.getTaskState() != null &&
                (mainTask.getTaskState() == 2 || mainTask.getTaskState() == 4)) {
            return false;
        }

        if (mainTask.getPlanEndTime() == null) {
            return false;
        }

        // 获取计划结束日期的23:59:59
        Calendar cal = Calendar.getInstance();
        cal.setTime(mainTask.getPlanEndTime());
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        Date endOfDay = cal.getTime();

        Date now = new Date();
        return now.after(endOfDay);
    }

    @Override
    public MainTask getTaskDetail(Integer mainId) {
        MainTask mainTask = mainTaskMapper.selectById(mainId);
        if (mainTask != null) {
            // 获取派发人详细信息
            AccountInfo distributor = accountMapper.findByUserId(mainTask.getUserId());
            if (distributor != null) {
                mainTask.setDistributor(distributor.getUserName());
            }

            // 获取执行人详细信息
            AccountInfo executor = accountMapper.findByUsername(mainTask.getExecutor());
            if (executor != null) {
                mainTask.setBelonging(executor.getCityName());
                mainTask.setExecutorAcName(executor.getAcName());
            } else {
                mainTask.setExecutorAcName("未知执行人");
            }

            // 获取子任务
            List<SubTask> subTasks = subTaskMapper.selectByMainId(mainId);

            if (subTasks != null && !subTasks.isEmpty()) {
                // 收集所有子任务ID
                List<Integer> subTaskIds = subTasks.stream()
                        .map(SubTask::getSubId)
                        .collect(Collectors.toList());

                // 批量查询所有批量子任务
                List<BatchSubTask> batchSubTasks = batchSubTaskMapper.selectBySubIds(subTaskIds);

                // 按子任务ID分组批量子任务
                Map<Integer, List<BatchSubTask>> batchSubTaskMap = batchSubTasks.stream()
                        .collect(Collectors.groupingBy(BatchSubTask::getSubId));

                for (SubTask subTask : subTasks) {
                    // 1. 处理多个执行人中文名称
                    String subExecutorAcNames = getExecutorAcNames(subTask.getSubExecutor());
                    subTask.setSubExecutorAcNames(subExecutorAcNames);

                    // 2. 计算批量子任务自评分平均值
                    List<BatchSubTask> batchTasks = batchSubTaskMap.getOrDefault(
                            subTask.getSubId(), Collections.emptyList());

                    double avgRating = calculateAvgRating(batchTasks);
                    subTask.setAvgRating(avgRating);

                    // 3. 设置执行人列表（用于前端显示）
                    subTask.setSubExecutors(subTask.getSubExecutors());
                    subTask.setSubBelongings(subTask.getSubBelongings());
                }
            }

            mainTask.setSubTasks(subTasks);
        }
        return mainTask;
    }

    // 计算批量子任务自评分平均值（保留两位小数）- DecimalFormat版本
    private double calculateAvgRating(List<BatchSubTask> batchTasks) {
        if (batchTasks == null || batchTasks.isEmpty()) {
            return 0.0;
        }

        double totalRating = 0.0;
        int count = 0;

        for (BatchSubTask batch : batchTasks) {
            if (batch.getSelfRating() != null) {
                // 确保评分在0-1之间
                double rating = Math.max(0, Math.min(1.0, batch.getSelfRating()));
                totalRating += rating;
                count++;
            }
        }

        if (count == 0) {
            return 0.0;
        }

        double rawAvg = totalRating / count;

        // 使用DecimalFormat保留两位小数
        DecimalFormat df = new DecimalFormat("#.##");
        return Double.parseDouble(df.format(rawAvg));
    }
    // 新增方法：根据用户名列表获取中文名列表
    private String getExecutorAcNames(String subExecutor) {
        if (subExecutor == null || subExecutor.isEmpty()) {
            return "";
        }

        List<String> executorNames = Arrays.asList(subExecutor.split(","));
        List<String> acNames = new ArrayList<>();

        for (String executor : executorNames) {
            AccountInfo account = accountMapper.findByUsername(executor);
            if (account != null) {
                acNames.add(account.getAcName());
            } else {
                acNames.add("未知执行人");
            }
        }

        return String.join(",", acNames);
    }
    @Override
    public Map<String, Object> getMainTasksByDistributor(
            String distributor,
            String mainName,
            String executor,
            Integer taskState,
            String taskType,
            String deptName,
            int pageNum,
            int pageSize) {

        int offset = (pageNum - 1) * pageSize;

        // 1. 查询任务列表
        List<MainTask> tasks = mainTaskMapper.selectTasksByDistributor(
                distributor, mainName, executor, taskState, taskType, deptName,
                offset, pageSize
        );

        // 2. 获取当前时间
        Date currentDate = new Date();

        // 3. 创建需要更新的任务列表
        List<MainTask> tasksToUpdate = new ArrayList<>();

        // 4. 遍历任务并更新状态
        for (MainTask task : tasks) {
            // 保存原始状态用于比较
            int originalState = task.getTaskState();

            // 5. 检查状态是否需要更新
            updateTaskState(task, currentDate);

            // 6. 如果状态发生变化，添加到更新列表
            if (task.getTaskState() != originalState) {
                tasksToUpdate.add(task);
            }

            // 7. 计算时间进度
            task.setTimeProgress(calculateTimeProgress(
                    task.getPlanBeginTime(),
                    task.getPlanEndTime(),
                    currentDate
            ));

            // 8. 计算任务进度（基于子任务）
            if (task.getTaskProgress() == null) {
                calculateTaskProgress(task);
            }

            // 9. 计算落实情况
            calculateTaskImplementation(task);
        }

        // 10. 批量更新状态变化的任务
        if (!tasksToUpdate.isEmpty()) {
            batchUpdateTaskStates(tasksToUpdate);
        }

        // 11. 查询总记录数
        int total = mainTaskMapper.countTasksByDistributor(
                distributor, mainName, executor, taskState, taskType, deptName
        );

        // 12. 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);

        // 13. 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", tasks);
        result.put("currentPage", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", total);
        result.put("totalPages", totalPages);
        return result;
    }
    // 更新任务状态的方法
    private void updateTaskState(MainTask task, Date currentDate) {
        if (task.getTaskState() == null || task.getTaskState() >= 2) {
            return; // 已完成或终止状态不更新
        }

        // 检查是否应该进入进行中状态
        if (task.getTaskState() == 0 &&
                currentDate.compareTo(task.getPlanBeginTime()) >= 0) {
            task.setTaskState(1);
        }

        // 检查是否应该进入延期状态 (超过计划结束日期的23:59:59)
        if (task.getTaskState() == 1 && task.getPlanEndTime() != null) {
            // 获取计划结束日期的23:59:59
            Calendar cal = Calendar.getInstance();
            cal.setTime(task.getPlanEndTime());
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 999);
            Date endOfDay = cal.getTime();

            if (currentDate.after(endOfDay)) {
                task.setTaskState(3);
            }
        }
    }

    // 批量更新任务状态
    private void batchUpdateTaskStates(List<MainTask> tasks) {
        for (MainTask task : tasks) {
            MainTask updateTask = new MainTask();
            updateTask.setMainId(task.getMainId());
            updateTask.setTaskState(task.getTaskState());
            mainTaskMapper.updateTaskState(updateTask);
        }
    }
    // 计算时间进度的方法
    private double calculateTimeProgress(Date planBeginTime, Date planEndTime, Date currentDate) {
        if (planBeginTime == null || planEndTime == null) {
            return 0.0;
        }

        if (currentDate.before(planBeginTime)) {
            return 0.0;
        }

        if (currentDate.after(planEndTime) || currentDate.equals(planEndTime)) {
            return 100.0;
        }

        long totalMillis = planEndTime.getTime() - planBeginTime.getTime();
        long elapsedMillis = currentDate.getTime() - planBeginTime.getTime();
        double progress = (double) elapsedMillis / totalMillis * 100;

        // 保留一位小数
        return Math.round(progress * 10.0) / 10.0;
    }

    // 计算任务进度（基于子任务）
    private void calculateTaskProgress(MainTask task) {
        if (task.getMainId() == null) return;

        List<SubTask> subTasks = subTaskMapper.findByMainId(task.getMainId());
        if (subTasks == null || subTasks.isEmpty()) {
            task.setTaskProgress(0.0);
            return;
        }

        double totalProgress = 0.0;
        for (SubTask sub : subTasks) {
            totalProgress += sub.getFinishProgress();
        }
        task.setTaskProgress(totalProgress / subTasks.size());
    }

    // 计算落实情况
    private void calculateTaskImplementation(MainTask task) {
        if (task.getTaskProgress() == null || task.getTimeProgress() == null) {
            task.setTaskImplementation("落后");
            return;
        }

        double diff = task.getTaskProgress() - task.getTimeProgress();
        if (diff > 5) {
            task.setTaskImplementation("超前");
        } else if (diff < -5) {
            task.setTaskImplementation("落后");
        } else {
            task.setTaskImplementation("正常");
        }
    }



    @Override
    public Map<String, Object> getTasksByExecutorOrSubExecutor(
            String currentUser,
            String mainName,
            Integer taskState,
            String taskType,
            String deptName,
            int pageNum,
            int pageSize) {

        int offset = (pageNum - 1) * pageSize;

        // 查询当前页数据
        List<MainTask> tasks = mainTaskMapper.selectTasksByExecutorOrSubExecutor(
                currentUser, mainName, taskState,taskType,deptName, offset, pageSize
        );

        // 获取当前时间
        Date currentDate = new Date();

        // 创建需要更新的任务列表
        List<MainTask> tasksToUpdate = new ArrayList<>();

        // 遍历任务并更新状态
        for (MainTask task : tasks) {
            int originalState = task.getTaskState();
            updateTaskState(task, currentDate);

            if (task.getTaskState() != originalState) {
                tasksToUpdate.add(task);
            }

            // 计算时间进度
            task.setTimeProgress(calculateTimeProgress(
                    task.getPlanBeginTime(),
                    task.getPlanEndTime(),
                    currentDate
            ));

            // 计算任务进度（如果为空）
            if (task.getTaskProgress() == null) {
                calculateTaskProgress(task);
            }

            // 计算落实情况
            calculateTaskImplementation(task);
        }

        // 批量更新状态变化的任务
        if (!tasksToUpdate.isEmpty()) {
            batchUpdateTaskStates(tasksToUpdate);
        }

        // 查询总记录数
        int total = mainTaskMapper.countTasksByExecutorOrSubExecutor(
                currentUser, mainName, taskState,taskType,deptName
        );

        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", tasks);
        result.put("currentPage", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", total);
        result.put("totalPages", totalPages);

        return result;
    }
    @Override
    public List<MainTaskWithSubTasksDTO> getAllTasksWithDetails(TaskAllQueryRequest request) {
        try {
            // 1. 查询主任务列表（带过滤条件）
            List<Map<String, Object>> mainTasks = mainTaskMapper.selectAllTasksWithDetails(request);

            if (CollectionUtils.isEmpty(mainTasks)) {
                return Collections.emptyList();
            }

            // 收集主任务ID
            List<Integer> mainIds = mainTasks.stream()
                    .map(row -> safeGetInteger(row, "mainId"))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            if (CollectionUtils.isEmpty(mainIds)) {
                return Collections.emptyList();
            }

            // 2. 批量查询子任务（只带归属地市过滤）
            List<SubTask> allSubTasks = subTaskMapper.selectByMainIdsAndCondition(
                    mainIds,
                    request.getSubBelonging(),
                    request.getSubExecutor()
            );

            // 收集子任务ID
            List<Integer> subTaskIds = allSubTasks.stream()
                    .map(SubTask::getSubId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 3. 批量查询批量子任务（带batchExecutor过滤）
            Map<Integer, List<BatchSubTask>> batchSubTaskMap = Collections.emptyMap();
            List<BatchSubTask> batchSubTasks = Collections.emptyList();

            if (!CollectionUtils.isEmpty(subTaskIds)) {
                // 调用新方法：selectBySubIdsAndCondition
                batchSubTasks = batchSubTaskMapper.selectBySubIdsAndCondition(
                        subTaskIds,
                        request.getBatchExecutor()
                );
                batchSubTaskMap = batchSubTasks.stream()
                        .collect(Collectors.groupingBy(BatchSubTask::getSubId));
            }

            // 4. 根据batchExecutor条件过滤子任务
            Set<Integer> validSubIds = new HashSet<>();
            if (!StringUtils.isEmpty(request.getBatchExecutor())) {
                batchSubTasks.stream()
                        .map(BatchSubTask::getSubId)
                        .forEach(validSubIds::add);
            }

            // 按主任务ID分组子任务（应用batchExecutor过滤）
            Map<Integer, List<SubTask>> subTaskMap = allSubTasks.stream()
                    .filter(subTask -> {
                        if (!StringUtils.isEmpty(request.getBatchExecutor())) {
                            return validSubIds.contains(subTask.getSubId());
                        }
                        return true;
                    })
                    .collect(Collectors.groupingBy(SubTask::getMainId));

            // 5. 确定子任务过滤条件
            boolean hasSubBelongingFilter = !StringUtils.isEmpty(request.getSubBelonging());
            boolean hasBatchExecutorFilter = !StringUtils.isEmpty(request.getBatchExecutor());
            boolean hasSubFilter = hasSubBelongingFilter || hasBatchExecutorFilter;

            // 6. 过滤主任务
            List<Map<String, Object>> filteredMainTasks = mainTasks.stream()
                    .filter(row -> {
                        Integer mainId = safeGetInteger(row, "mainId");
                        if (mainId == null) return false;
                        return !hasSubFilter || subTaskMap.containsKey(mainId);
                    })
                    .collect(Collectors.toList());

            if (CollectionUtils.isEmpty(filteredMainTasks)) {
                return Collections.emptyList();
            }

            // 7. 构建账户信息缓存（包含子任务执行人和批量子任务执行人）
            Map<String, AccountInfo> accountCache = buildExtendedAccountCache(allSubTasks, batchSubTasks);

            // 8. 构建最终结果
            List<MainTaskWithSubTasksDTO> result = new ArrayList<>();
            for (Map<String, Object> row : filteredMainTasks) {
                Integer mainId = safeGetInteger(row, "mainId");
                if (mainId == null) continue;

                MainTaskWithSubTasksDTO dto = new MainTaskWithSubTasksDTO();
                // 设置主任务字段（保持不变）
                dto.setMainId(mainId);
                dto.setMainName(safeGetString(row, "mainName"));
                dto.setMainDescription(safeGetString(row, "mainDescription"));
                dto.setDistributor(safeGetString(row, "distributor"));
                dto.setExecutor(safeGetString(row, "executor"));
                dto.setBelonging(safeGetString(row, "belonging"));
                dto.setPhone(safeGetString(row, "phone"));
                dto.setTaskProgress(safeGetDouble(row, "taskProgress"));
                dto.setTimeProgress(safeGetDouble(row, "timeProgress"));
                dto.setTaskImplementation(safeGetString(row, "taskImplementation"));
                dto.setTaskState(safeGetInteger(row, "taskState"));
                dto.setUserId(safeGetInteger(row, "userId"));
                dto.setPlanBeginTime(safeGetDate(row, "planBeginTime"));
                dto.setPlanEndTime(safeGetDate(row, "planEndTime"));
                dto.setActualFinishTime(safeGetDate(row, "actualFinishTime"));
                dto.setExecutorAcName(safeGetString(row, "executorAcName"));
                dto.setExecutorCityName(safeGetString(row, "executorCityName"));
                dto.setTaskType(safeGetString(row, "taskType"));
                dto.setSpecializedName(safeGetString(row, "specializedName"));
                dto.setDeptName(safeGetString(row,"deptName"));

                // 设置子任务
                List<SubTask> subTasks = subTaskMap.getOrDefault(mainId, Collections.emptyList());
                List<SubTaskWithBatchDTO> subTaskDTOs = new ArrayList<>();

                for (SubTask subTask : subTasks) {
                    SubTaskWithBatchDTO subDTO = new SubTaskWithBatchDTO();
                    BeanUtils.copyProperties(subTask, subDTO);

                    // 设置子任务执行人中文名
                    setSubExecutorAcNames(subDTO, accountCache);

                    // 设置批量子任务
                    Integer subId = subTask.getSubId();
                    List<BatchSubTask> batchTasks = batchSubTaskMap.getOrDefault(subId, Collections.emptyList());

                    List<BatchSubTaskDTO> batchDTOs = batchTasks.stream()
                            .map(batch -> {
                                BatchSubTaskDTO batchDTO = new BatchSubTaskDTO();
                                BeanUtils.copyProperties(batch, batchDTO);

                                // 设置批量子任务执行人中文名
                                setBatchExecutorAcName(batchDTO, accountCache);

                                return batchDTO;
                            })
                            .collect(Collectors.toList());

                    subDTO.setBatchSubTasks(batchDTOs);

                    // 计算并设置平均评分
                    double avgRating = calculateAvgRating(batchTasks);
                    subDTO.setAvgRating(avgRating);

                    subTaskDTOs.add(subDTO);
                }

                dto.setSubTasks(subTaskDTOs);
                result.add(dto);
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询任务详情失败: " + e.getMessage(), e);
        }
    }

    // 构建扩展的账户缓存（包含子任务和批量子任务执行人）
    private Map<String, AccountInfo> buildExtendedAccountCache(List<SubTask> subTasks, List<BatchSubTask> batchSubTasks) {
        Set<String> usernames = new HashSet<>();

        // 收集子任务执行人
        for (SubTask subTask : subTasks) {
            if (!StringUtils.isEmpty(subTask.getSubExecutor())) {
                String[] executors = subTask.getSubExecutor().split(",");
                for (String executor : executors) {
                    usernames.add(executor.trim());
                }
            }
        }

        // 收集批量子任务执行人
        for (BatchSubTask batchTask : batchSubTasks) {
            if (!StringUtils.isEmpty(batchTask.getBatchExecutor())) {
                usernames.add(batchTask.getBatchExecutor().trim());
            }
        }

        // 批量查询账户信息
        if (!usernames.isEmpty()) {
            List<AccountInfo> accounts = accountMapper.findByUsernames(new ArrayList<>(usernames));
            return accounts.stream()
                    .collect(Collectors.toMap(AccountInfo::getUserName, Function.identity()));
        }

        return Collections.emptyMap();
    }

    // 设置批量子任务执行人中文名
    private void setBatchExecutorAcName(BatchSubTaskDTO batchDTO, Map<String, AccountInfo> accountCache) {
        if (StringUtils.isEmpty(batchDTO.getBatchExecutor())) {
            return;
        }

        AccountInfo account = accountCache.get(batchDTO.getBatchExecutor().trim());
        if (account != null && account.getAcName() != null) {
            batchDTO.setBatchExecutorAcName(account.getAcName());
        } else {
            batchDTO.setBatchExecutorAcName("未知执行人");
        }
    }

    // 设置子任务执行人中文名（使用缓存）
    private void setSubExecutorAcNames(SubTaskWithBatchDTO subDTO, Map<String, AccountInfo> accountCache) {
        if (subDTO.getSubExecutor() == null || subDTO.getSubExecutor().isEmpty()) {
            return;
        }

        String[] executors = subDTO.getSubExecutor().split(",");
        List<String> acNames = new ArrayList<>();

        for (String executor : executors) {
            AccountInfo account = accountCache.get(executor.trim());
            if (account != null && account.getAcName() != null) {
                acNames.add(account.getAcName());
            } else {
                acNames.add("未知执行人");
            }
        }

        subDTO.setSubExecutorAcNames(String.join(",", acNames));
    }

    // 安全获取Integer类型值
    private Integer safeGetInteger(Map<String, Object> row, String key) {
        Object value = row.get(key);
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    // 安全获取Double类型值
    private Double safeGetDouble(Map<String, Object> row, String key) {
        Object value = row.get(key);
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        try {
            return Double.parseDouble(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    // 安全获取String类型值
    private String safeGetString(Map<String, Object> row, String key) {
        Object value = row.get(key);
        return value != null ? value.toString() : null;
    }

    // 安全获取Date类型值
    private Date safeGetDate(Map<String, Object> row, String key) {
        Object value = row.get(key);
        if (value instanceof Date) {
            return (Date) value;
        }
        return null;
    }

    // 获取子任务及其批量子任务
    private List<SubTaskWithBatchDTO> getSubTasksWithBatch(Integer mainId) {
        // 获取子任务
        List<SubTask> subTasks = subTaskMapper.selectByMainId(mainId);
        List<SubTaskWithBatchDTO> result = new ArrayList<>();

        for (SubTask subTask : subTasks) {
            SubTaskWithBatchDTO dto = new SubTaskWithBatchDTO();
            BeanUtils.copyProperties(subTask, dto);

            // 设置子任务执行人中文名
            setSubExecutorAcNames(dto);

            // 获取批量子任务
            dto.setBatchSubTasks(getBatchSubTasks(subTask.getSubId()));

            result.add(dto);
        }

        return result;
    }

    // 设置子任务执行人中文名
    private void setSubExecutorAcNames(SubTaskWithBatchDTO subTask) {
        if (subTask.getSubExecutor() == null || subTask.getSubExecutor().isEmpty()) {
            return;
        }

        String[] executors = subTask.getSubExecutor().split(",");
        List<String> acNames = new ArrayList<>();

        for (String executor : executors) {
            AccountInfo account = accountMapper.findByUsername(executor.trim());
            if (account != null && account.getAcName() != null) {
                acNames.add(account.getAcName());
            } else {
                acNames.add("未知执行人");
            }
        }

        subTask.setSubExecutorAcNames(String.join(",", acNames));
    }

    // 获取批量子任务
    private List<BatchSubTaskDTO> getBatchSubTasks(Integer subId) {
        List<BatchSubTask> batchSubTasks = batchSubTaskMapper.selectBySubId(subId);
        List<BatchSubTaskDTO> result = new ArrayList<>();

        for (BatchSubTask batch : batchSubTasks) {
            BatchSubTaskDTO dto = new BatchSubTaskDTO();
            BeanUtils.copyProperties(batch, dto);
            result.add(dto);
        }

        return result;
    }

    @Override
    public List<SubTask> findSubtasksByMainTaskType(String taskType, String subName) {
        // 处理模糊查询参数
        String searchName = StringUtils.isNotBlank(subName)
                ? "%" + subName.trim() + "%"
                : null;
        return subTaskMapper.selectByMainTaskType(taskType, searchName);
    }
    @Override
    public Map<String, Object> getTaskOverview(String currentUser) {
        Map<String, Object> result = new HashMap<>();

        // 2. 派发数（派发人是当前用户的总数）
        int distributedCount = mainTaskMapper.countDistributedTasks(currentUser);
        result.put("distributeCount", distributedCount);

        // 3. 接收数（主任务执行人是当前用户的总数）
        int receivedCount = mainTaskMapper.countReceivedTasks(currentUser);
        result.put("executorCount", receivedCount);

        // 4. 已完成（执行人是当前用户且taskState=2的条数）
        int completedCount = mainTaskMapper.countCompletedTasks(currentUser);
        result.put("completeCount", completedCount);


        // 6. 进行中（当前用户作为子任务执行人且子任务进度小于100的条数）
        int inProgressCount = mainTaskMapper.countInProgressTasks(currentUser);
        result.put("inProgressCount", inProgressCount);

        // 7. 本月关键结果（当前用户作为批量子任务执行人的所有批量子任务数量总和）
        int monthlyKeyResults = mainTaskMapper.countMonthlyKeyResults(currentUser);
        result.put("monthKeyResults", monthlyKeyResults);

        // 8. 我的关键结果已完成（当前用户作为子任务执行人且子任务进度等于100的数量总和）
        int completedKeyResults = mainTaskMapper.countCompletedKeyResults(currentUser);
        result.put("completeKeyResults", completedKeyResults);

        return result;
    }
}
class SubTaskRequest {
    private String subName;
    private String subDescription;
    private String subExecutor;      // 子任务执行人
    private String subBelonging;     // 子任务归属组织

    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date planStartTime;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date planFinishTime;
    private List<String> subExecutors;  // 改为列表，支持多个执行人

    public List<String> getSubExecutors() {
        return subExecutors;
    }

    public void setSubExecutors(List<String> subExecutors) {
        this.subExecutors = subExecutors;
    }

    // getters and setters
    public String getSubName() { return subName; }
    public void setSubName(String subName) { this.subName = subName; }
    public String getSubDescription() { return subDescription; }
    public void setSubDescription(String subDescription) { this.subDescription = subDescription; }

    public String getSubExecutor() {
        return subExecutor;
    }

    public void setSubExecutor(String subExecutor) {
        this.subExecutor = subExecutor;
    }

    public String getSubBelonging() {
        return subBelonging;
    }

    public void setSubBelonging(String subBelonging) {
        this.subBelonging = subBelonging;
    }

    public Date getPlanStartTime() { return planStartTime; }
    public void setPlanStartTime(Date planStartTime) { this.planStartTime = planStartTime; }
    public Date getPlanFinishTime() { return planFinishTime; }
    public void setPlanFinishTime(Date planFinishTime) { this.planFinishTime = planFinishTime; }
}